<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <!-- v-if="checkPermission('EXCEL_IMPORT')" -->
          <el-button
            v-permission="'EXCEL_IMPORT'"
            type="warning"
            size="small"
            @click="$router.push('/import?type=user')"
          >excel导入</el-button>
          <!-- v-if="checkPermission('EXCEL_EXPORT')" -->
          <el-button
            v-permission="'EXCEL_EXPORT'"
            type="danger"
            size="small"
            @click="exportExcel"
          >excel导出</el-button>
          <!-- v-if="checkPermission('ADD_EMP')" -->
          <el-button
            v-permission="'ADD_EMP'"
            type="primary"
            size="small"
            @click="addEmployeeFn"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card v-loading="isLoading" style="margin-top: 10px">
        <el-table border :data="list">
          <el-table-column
            label="序号"
            type="index"
            width="100"
            :index="indexMethod"
          />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{ row }">
              <img v-imgerror="img404" :src="row.staffPhoto||defaultImg" class="staff">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            :formatter="formatterFormOfEmpment"
          />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{ row }">
              {{ formateTime(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{ row }">
              <!-- v-if="checkPermission('EMP_CHANGE')" -->
              <el-button
                v-permission="'EMP_CHANGE'"
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <!-- v-if="checkPermission('EMP_ASSIGNROLE')" -->
              <el-button
                v-permission="'EMP_ASSIGNROLE'"
                type="text"
                size="small"
                @click="assignRole(row.id)"
              >分配角色</el-button>
              <!-- v-if="checkPermission('EMP_DELEMPLOYEES')" -->
              <el-button
                v-permission="'EMP_DELEMPLOYEES'"
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-size="size"
            layout="total,prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <addEmployee :show-dialog.sync="showDialog" />
      <assignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmployeeListApi, delEmployeeApi } from '@/api/employees'
import enumObj from '@/constant/employees'
import dayjs from 'dayjs'
import addEmployee from './components/add-employee.vue'
import assignRole from './components/assign-role.vue'

// 1.导入
import permission from '@/mixins/permission'
export default {
  name: 'Approvals',
  components: {
    addEmployee,
    assignRole
  },
  // 混入
  mixins: [permission],
  data() {
    return {
      page: 1,
      size: 10,
      list: [],
      total: 0,
      isLoading: false,
      showDialog: false,
      defaultImg: 'https://img1.baidu.com/it/u=3870557935,2333078440&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
      img404: 'https://image.uisdc.com/wp-content/uploads/2013/09/1379411391_1436653066_9750_imageAddr.jpg',
      showRoleDialog: false,
      userId: ''
    }
  },

  created() {
    this.getEmployeeList()
  },
  methods: {
    assignRole(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    /**
     * 导出excel文件
     */
    async exportExcel() {
      const {
        data: { rows }
      } = await getEmployeeListApi(1, this.total)
      const headersArr = [
        '姓名',
        '手机号',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
      const headersRelations = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const arr = this.formateData(rows, headersArr, headersRelations)
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          // 导出的表头
          header: headersArr,
          // 导出的数据
          data: arr,
          // 文件名
          filename: '员工信息',
          // 单元格的宽度是否自适应
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    formateData(rows, headersArr, headersRelations) {
      const result = []
      rows.forEach((item) => {
        const tempArr = []
        headersArr.forEach((key) => {
          const englishKey = headersRelations[key]
          let value = item[englishKey]
          // 时间的处理
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = this.formateTime(item[englishKey])
          }
          // 聘用形式
          if (englishKey === 'formOfEmployment') {
            const hireType = enumObj.hireType
            const r = hireType.find((item) => item.id === Number(value))
            value = r ? r.value : '未知'
          }
          tempArr.push(value)
        })
        result.push(tempArr)
      })
      return result
    },
    /**
     * 添加员工
     */
    addEmployeeFn() {
      this.showDialog = true
    },
    /**
     * 删除员工
     */
    delEmployee(id) {
      this.$confirm('亲！您确定要删除吗？', '温馨提示')
        .then(async() => {
          // 表示用户点击了确定按钮
          await delEmployeeApi(id)
          this.$message.success('删除成功')
          if (this.list.length === 1 && this.page > 1) {
            this.page--
          }
          this.getEmployeeList()
        })
        .catch(() => {})
    },
    /**
     * 转换时间
     */
    formateTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    },
    /**
     * 格式化聘用形式
     */
    formatterFormOfEmpment(row, column, cellValue, index) {
      // if (Number(cellValue) === 1) {
      //   return '正式'
      // } else if (Number(cellValue) === 2) {
      //   return '非正式'
      // } else {
      //   return '未知'
      // }
      const hireType = enumObj.hireType
      const result = hireType.find((item) => item.id === Number(cellValue))
      return result ? result.value : '未知'
    },
    /**
     * 计算索引
     */
    indexMethod(index) {
      return (this.page - 1) * this.size + index + 1
    },
    /**
     * 页码发生变化
     */
    handleCurrentChange(val) {
      this.page = val
      this.getEmployeeList()
    },
    /**
     * 获取员工列表
     */
    async getEmployeeList() {
      this.isLoading = true
      const { data } = await getEmployeeListApi(this.page, this.size)
      this.list = data.rows
      this.total = data.total
      this.isLoading = false
    }
  }
}
</script>

<style scoped lang="scss">
.staff {
  width: 70px;
  height: 70px;
  border-radius: 50%;
}
</style>
